<template>
  <div class="home">
    主页
    <el-button type="primary" @click="tryToShare">点击分享</el-button>
    <el-button type="primary" @click="go2Mini">跳出去</el-button>
    <el-button type="primary" @click="go2Schema">openSchema</el-button>
    <el-button type="primary" @click="scanCode">scanCode</el-button>
    <el-button type="primary" @click="h5Config">鉴权</el-button>
    <el-button type="primary" @click="download2File">下载</el-button>
    <el-button type="primary" @click="testAlert">发消息卡片</el-button>
    <el-button type="primary" @click="testNFC">nfc-test</el-button>
    <el-button type="primary" @click="chooseVideo">chooseVideo</el-button>


    <div id="qCode" style="width: 200px;height: 200px"></div>
  </div>
</template>

<script>
import {httpClient} from '@/utils/request';
import lark from '@/config';

export default {
  name: 'home',
  components: {},
  async mounted() {
    // document.title = 'abc \n asjhas';
    // await this.config();
    const CLIENT_ID = 'cli_a03ee1eb59b9500e';
    const REDIRECT_URI = encodeURIComponent('https://baidu.com');
    setTimeout(() => {
      const QRLoginObj = QRLogin({
        id: 'qCode',
        goto: `https://www.feishu.cn/suite/passport/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&state=STATE`,
        width: '500',
        height: '500',
      });
      console.log(QRLoginObj);
      const handleMessage = function(event) {
        const origin = event.origin;
        // 使用 matchOrigin 方法来判断 message 是否来自飞书页面
        if (QRLoginObj.matchOrigin(origin)) {
          console.log(event);
          const loginTmpCode = event.data;
          // 在授权页面地址上拼接上参数 tmp_code，并跳转
          window.location.href = `https://192.168.0.103:3000/auth/v2/qcode_auth?tmp_code=${loginTmpCode}`;
        }
      };
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage);
      }
    }, 300);
  },
  methods: {
    async h5Config() {
      // 判断飞书环境
      await httpClient.get({
        url: lark.env.api.AUTH.V2_GET_APP_TOKEN,
      });
      const sdkContent = await httpClient.get({
        url: lark.env.api.AUTH.V2_JS_SDK,
        params: {
          url: lark.env.runtime.hashRouter ? window.location.href.split('#')[0] : window.location.href,
        },
      });
      const {appId, timestamp, signature, nonceStr} = sdkContent.data.data;
      console.log(appId, '---', timestamp, '---', signature, '----', nonceStr);
      window.h5sdk.config({
        appId, // 必填，应用ID
        timestamp, // 必填，生成签名的时间戳，ms级
        nonceStr, // 必填，生成签名的随机串
        signature, // 必填，签名
        jsApiList: [],
        onSuccess: (res) => {
          console.log('鉴权结果：', res);
          console.log(`config: success ${JSON.stringify(res)}`);
          // tt.openSetting({
          //   success(res) {
          //     console.log(res);
          //   },
          //   fail(res) {
          //     console.log(res);
          //   },
          // });
          tt.getUserInfo({
            success(res) {
              console.log(res);
            },
            fail(res) {
              console.log(res);
            },
          });
        },
        onFailed: (res) => {
          console.log(`config: fail ${JSON.stringify(res)}`, 'test');
        },
      });
      window.h5sdk.error((err) => {
        console.error(JSON.stringify(err));
      });
    },
    testAlert() {
      tt.sendMessageCard({
        openChatIDs: ['ou_5de292512c1248ef5c866dd452fa2e28', 'oc_a8fa511557bc9d896ee67104e2726238'],
        cardContent: {
          msg_type: 'interactive',
          update_multi: false,
          card: {
            'config': {
              'wide_screen_mode': true,
            },
            'header': {
              'title': {
                'tag': 'plain_text',
                'content': 'this is header',
              },
            },
            'elements': [{
              'tag': 'div',
              'text': {
                'tag': 'plain_text',
                'content': 'This is a very very very very very very very long text;',
              },
            }, {
              'tag': 'action',
              'actions': [{
                'tag': 'button',
                'text': {
                  'tag': 'plain_text',
                  'content': 'Read',
                },
                'type': 'default',
              }],
            }],
          },
        },
        success(res) {
          console.log(`sendMessageCard 调用成功`);
        },
        fail(res) {
          console.log(`sendMessageCard 调用失败`);
        },
      });
    },
    tryToShare() {
      window.h5sdk.biz.util.share({
        url: 'https://applink.feishu.cn/client/web_app/open?appId=cli_a03ee1eb59b9500e&path=/confirmInfo/appBaseInfo&mode=window',
        title: 'Open platform',
        image: '…/example.png',
        content: 'Quickly develop apps and introduce services with a user-friendly IDE',
        onSuccess: function(result) {
          console.log(result);
        },
      });
    },
    go2Mini() {
      tt.miniProgram.navigateBack({
        delta: 1,
        success(res) {
          console.log(`${res}`);
        },
        fail(res) {
          console.log(`navigateBack 调用失败`);
        },
      });
    },
    chooseVideo() {
      tt.chooseVideo({
        sourceType: ['camera'],
        compressed: true,
        success(res) {
          console.log(res);
        },
        fail(res) {
          console.log(`chooseVideo 调用失败`);
        },
      });
    },
    testNFC() {
      console.log('55555');
      const adapter = tt.getNFCAdapter();
      console.log(adapter);
      adapter.startDiscovery({
        success(res) {
          if (!action) {
            console.log(res);
          }
        },
        fail(err) {
          console.log(err);
        },
      });
      adapter.onDiscovered(
          (res) => {
            console.log(res);
            // 扫描到NFC标签后
            const nfcA = adapter.getNfcA();
            const gNfcUid = Array.from(new Uint8Array(res.uid));
            console.log('uid: ', gNfcUid);
            // 连接NFCA标签
            nfcA.connect({
              success(res) {
                console.log(JSON.stringify(res));
                const gNfcUid = Array.from(new Uint8Array(res.uid));
                console.log('uid: ', gNfcUid);
              },
              fail(err) {
                console.log(JSON.stringify(err));
              },
            });
          },
      );
    },
    download2File() {
      tt.downloadFile({
        // 示例 url
        url: 'http://www.leomay.com/upload/file/mmo-20170707165001.pdf',
        success(res) {
          console.log(res);
          const filePath = res.tempFilePath;
          tt.openDocument({
            filePath,
            success(res) {
              console.log('打开文档成功');
            },
          });
        },
      });
    },
    go2Schema() {
      tt.openSchema({
        schema: 'alipays://platformapi/startapp?appId=20000123',
        external: false,
        success(res) {
          console.log(res);
        },
        fail(res) {
          console.log(res);
        },
      });
    },
    scanCode() {
      tt.scanCode({
        barCodeInput: true,
        success(res) {
          console.log(`${res.result}`);
        },
        fail(res) {
          console.log(`scanCode 调用失败`);
        },
      });
    },
  },
};
</script>
